﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace ImportDB
{
    public partial class Form1 : Form
    {
        DateTime st = DateTime.Now;
        private DataTable dtTemp;
        private MysqlHelper MySqlHelper;
        private Dictionary<string, int> ColWidths;

        public Form1()
        {
            InitializeComponent();
        }



        private void EndOpen()
        {
            toolStriplabStatus.Text = System.IO.Path.GetFileName(labTable.Text);
            toolStripPB.Visible = false;
            this.Cursor = Cursors.Default;
            timer1.Enabled = false;
        }

        private void StartOpen()
        {
            st = DateTime.Now;
            gv.DataSource = null;
            toolStripPB.Visible = true;
            toolStriplabStatus.Text = "opening...";
            timer1.Enabled = true;
            this.Cursor = Cursors.WaitCursor;
        }

        private void btnSelectFile_Click(object sender, EventArgs e)
        {


            if (OFD.ShowDialog() == DialogResult.OK)
            {
                labTable.Text = OFD.FileName;
                StartOpen();
                BW.RunWorkerAsync();
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            toolStripLabTimeElapsed.Text = (DateTime.Now - st).ToString().Substring(0, 8);
        }

        private void BW_DoWork(object sender, DoWorkEventArgs e)
        {

            IPlainDataFile plainDataFile = PlainDataFileFactory.Instance.GetPlainDatafile(labTable.Text);
            e.Result = plainDataFile.GetDataTable();

        }

        private void BW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                EndOpen();
                MessageBox.Show(e.Error.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                DataTable dt = e.Result as DataTable;
                this.ColWidths = GetColWidth(dt);
                gv.DataSource = dt;
                GetColWidth(dt);
                toolStripLabRecs.Text = "Total rows:" + dt.Rows.Count.ToString();
                EndOpen();

                dtTemp = dt;
                button1.Enabled = true;
            }

        }

        private Dictionary<string, int> GetColWidth(DataTable argdt)
        {
            Dictionary<string, int> ditCols = new Dictionary<string, int>();
            foreach (DataColumn col in argdt.Columns)
            {
                ditCols.Add(col.ColumnName, 50);
            }
            foreach (DataRow row in argdt.Rows)
            {
                foreach (DataColumn col in argdt.Columns)
                {
                    int valueWidth = row[col].ToString().Length;
                    if (valueWidth > ditCols[col.ColumnName])
                    {
                        ditCols[col.ColumnName] = valueWidth + 10;
                    }
                }
            }
            return ditCols;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            toolStripPB.Visible = true;
            toolStripPB.Style = ProgressBarStyle.Blocks;
            timer1.Enabled = true;
            st = DateTime.Now;
            bwImport.RunWorkerAsync();
        }

        private void ImportData(System.ComponentModel.BackgroundWorker argWorker)
        {
            string server = Properties.Settings.Default.mysqlserver;
            string db = Properties.Settings.Default.mysqldb;
            string uid = Properties.Settings.Default.mysqluid;
            string pwd = Properties.Settings.Default.mysqlpwd;
            string err = string.Empty;
            this.MySqlHelper = MysqlHelper.GetMysqlHelper(server, db, uid, pwd, err);
            if (this.MySqlHelper == null)
            {
                MessageBox.Show("Invalid database parameters. Please configure it.\r\n" + err);
            }
            else
            {
                this.MySqlHelper.ImportData(this.dtTemp, GetTableName(labTable.Text), this.ColWidths,argWorker);
                
            }
        }

        private string GetTableName(string argFilePath)
        {
            return System.IO.Path.GetFileName(argFilePath).Replace('.', '_').Replace(' ', '_').Replace('-','_');
        }

        private void bwImport_DoWork(object sender, DoWorkEventArgs e)
        {
            ImportData(sender as BackgroundWorker);
        }

        private void bwImport_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            toolStripPB.Value = e.ProgressPercentage;
            toolStriplabStatus.Text = string.Format("importing... {0}%", e.ProgressPercentage);
        }

        private void bwImport_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            toolStriplabStatus.Text = "Complete!";
            timer1.Enabled = false;
        }

        private void btnSetting_Click(object sender, EventArgs e)
        {
            frmSetting frmsetting = new frmSetting();
            frmsetting.ShowDialog();
        }
    }
}
